<template>
	<div class="comments">
		<comment-list
			v-if="userInfo.openId"
			type="user"
			:comments="comments"
		></comment-list>
		<template v-if="userInfo.openId">
			<div class="page-title">我的图书</div>
			<card
				v-for="book in books"
				:key="book.isbn"
				:book="book"
			></card>
			<div v-if='!books.length' style="text-align: center;margin-bottom: 10px;">暂时还没添加过书，快去添加几本把</div>
		</template>
		<div v-else style="margin-top: 100px;">
			<div style="text-align: center;margin-bottom: 10px;">您还没登录，暂时无法查看</div>
			<button class="btn" @click="toLogin">去登录</button>
		</div>
	</div>
</template>
<script>
import { get } from '@/utils/api'

import commentList from '@/components/commentList'
import card from '@/components/card'

export default {
  name: 'comments',
  data () {
    return {
      comments: [],
      books: [],
      userInfo: {}
    }
  },
  components: {
    commentList,
    card
  },
  onShow () {
    if (!this.userInfo.openId) {
      let userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
        this.init()
      }
    }
  },
  onPullDownRefresh () {
    this.init()
    wx.stopPullDownRefresh()
  },
  methods: {
    init () {
      wx.showNavigationBarLoading()
      this.getComments()
      this.getBookList()
      wx.hideNavigationBarLoading()
    },
    toLogin () {
      wx.switchTab({
        url: '/pages/me/main'
      })
    },
    async getBookList () {
      let booklist = await get('/weapp/booklist', { openId: this.userInfo.openId })
      if (booklist.code === 0) {
        this.books = booklist.data.books
      }
    },
    async getComments () {
      let comments = await get('/weapp/commentlist', { openId: this.userInfo.openId })
      this.comments = comments.data.commentList || []
      if (this.comments.length) {
        this.comments.map(item => {
          item.createTime = this.formatTime(item.create_time, 'Y-M-D h:m:s')
          delete item.create_time
        })
      }
    },
    // 格式化日期，如月、日、时、分、秒保证为2位数
    formatNumber (n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    // 参数number为毫秒时间戳，format为需要转换成的日期格式
    formatTime (number, format) {
      let time = new Date(number)
      let newArr = []
      let formatArr = ['Y', 'M', 'D', 'h', 'm', 's']
      newArr.push(time.getFullYear())
      newArr.push(this.formatNumber(time.getMonth() + 1))
      newArr.push(this.formatNumber(time.getDate()))

      newArr.push(this.formatNumber(time.getHours()))
      newArr.push(this.formatNumber(time.getMinutes()))
      newArr.push(this.formatNumber(time.getSeconds()))

      for (let i in newArr) {
        format = format.replace(formatArr[i], newArr[i])
      }
      return format
    }
  }
}
</script>
<style lang="scss" scoped>
	// .comments
</style>